import requests
from pyquery import PyQuery as pq
from urllib.request import urlretrieve


#爬取页面信息
def getPage(url):
	'''获取购物车网页信息'''
	# 伪装头信息	
	headers = {
		'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
		'Accept-Encoding':'gzip, deflate, sdch, br',
		'Accept-Language':'zh-CN,zh;q=0.8',
		'Cache-Control':'max-age=0',
		'Connection':'keep-alive',
		'Cookie':'user-key=b72cedf2-5386-4fab-aeb7-c01e0a8268be',
		'Host':'cart.jd.com',
		'Upgrade-Insecure-Requests':'1',
		'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2969.0 Safari/537.36'
	}
	try:
		html = requests.get(url,headers=headers)
		if html.status_code == 200:
			res = html.text		
			return res
		else:
			return None
	except Exception:
		return None


#解析网页信息
def parsePage(content):
	#解析
	doc = pq(content)
	#获取所有的标签
	items = doc("div.item-selected").items()
	#print('2222')
	#遍历封装并输出
	for item in items:
		
		name = item.find("div.item-msg div.p-name a").text()

		price = item.find('p.plus-switch').text()

		img = item.find("div.p-img img").attr('src').replace("cms/s80x80_","n1/")
		
		print("商品名称："+name+";\n"+"价格："+price+"元;\n"+"图片："+img+";")

#主程序函数
def main(url):
	
	html = getPage(url)
	#print('000')

	if html:
		parsePage(html)
	else:
		print("未爬取到信息！")


#判断是否为主程序运行，并遍历调用主函数爬取数据
if __name__ == '__main__':
	url = 'https://cart.jd.com/cart.action'
	main(url)
#